<template>
  <ContentWrap :title="title">
    <Form
      :schema="schema"
      :model="empData"
      @register="formRegister"
      label-width="120px"
      :rules="rules"
    />
    <div style="width: 100%; text-align: center; margin-top: 20px">
      <el-space>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="callback">返回</el-button>
      </el-space>
    </div>
  </ContentWrap>
</template>

<script>
import { Form } from '@/components/Form'
import { HrItemDic, HrEnumDic } from '@/config/publicDic'
import * as empApi from '@/api/emp/emp'
import { useUserStoreWithOut } from '@/store/modules/user'
import { colProps } from 'element-plus'
import { useForm } from '@/hooks/web/useForm'
import { IsNull } from '@/utils'
import { isIDCard, isLetterAndInt, isPhone, isTelephone, validEmail } from '@/utils/is'
const { formRegister, formMethods } = useForm()
export default {
  components: {
    Form
  },
  data() {
    const vaildatePhone = async (rule, value, callback) => {
      if (IsNull(value)) {
        callback()
      } else if (isPhone(value) === false) {
        callback(new Error('手机号格式错误!'))
      } else if (await this.checkRepeat(0, value)) {
        callback(new Error('手机号重复!'))
      } else {
        callback()
      }
    }
    const vaildateEmail = async (rule, value, callback) => {
      if (IsNull(value)) {
        callback()
      } else if (value && validEmail(value) === false) {
        callback(new Error('Email格式错误!'))
      } else if (await this.checkRepeat(3, value)) {
        callback(new Error('Email重复!'))
      } else {
        callback()
      }
    }
    const vaildateTelephone = (rule, value, callback) => {
      if (IsNull(value)) {
        callback()
      } else if (isTelephone(value) === false) {
        callback(new Error('备用联系电话格式错误!'))
      } else {
        callback()
      }
    }
    const vaildateIDCard = async (rule, value, callback) => {
      if (IsNull(value)) {
        callback()
      } else if (isIDCard(value) === false) {
        callback(new Error('身份证号格式错误!'))
      } else if (await this.checkRepeat(2, value)) {
        callback(new Error('身份证号重复!'))
      } else {
        callback()
      }
    }
    const validateEmpNo = async (rule, value, callback) => {
      if (IsNull(value)) {
        callback()
      } else if (isLetterAndInt(value) === false) {
        callback(new Error('员工编号应由数字和字母构成!'))
      } else if (await this.checkRepeat(1, value)) {
        callback(new Error('员工编号重复!'))
      } else {
        callback()
      }
    }
    return {
      empId: null,
      schema: [],
      empData: {},
      title: '新增员工',
      rules: {
        EmpName: [
          {
            required: true,
            message: '员工名不能为空！',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 100,
            message: '员工名长度在 2 到 100 个字之间',
            trigger: 'blur'
          }
        ],
        DeptId: [
          {
            required: true,
            message: '请选择部门',
            trigger: 'blur'
          }
        ],
        UserType: [
          {
            required: true,
            message: '请选择员工类型',
            trigger: 'blur'
          }
        ],
        Phone: [
          {
            required: true,
            message: '手机号不能为空！',
            trigger: 'blur'
          },
          {
            min: 11,
            max: 15,
            message: '手机号格式错误!',
            trigger: 'blur'
          },
          {
            required: true,
            trigger: 'blur',
            validator: vaildatePhone
          }
        ],
        Email: [
          {
            required: false,
            trigger: 'blur',
            validator: vaildateEmail
          }
        ],
        IDCard: [
          {
            required: false,
            trigger: 'blur',
            validator: vaildateIDCard
          }
        ],
        BackupPhone: [
          {
            required: false,
            trigger: 'blur',
            validator: vaildateTelephone
          }
        ],
        EmpNo: [
          {
            required: true,
            message: '员工编号不能为空！',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 20,
            message: '员工编号长度在 2 到 50 个字符之间!',
            trigger: 'blur'
          },
          {
            required: true,
            trigger: 'blur',
            validator: validateEmpNo
          }
        ]
      }
    }
  },
  computed: {
    comId() {
      return useUserStoreWithOut().comId
    }
  },
  mounted() {
    this.empId = this.$route.params.id
    this.reset()
  },
  methods: {
    formRegister,
    callback() {
      this.$router.replace({ name: 'emp' })
    },
    async checkRepeat(type, value) {
      return await empApi.checkRepeat({
        EmpId: this.empId,
        CompanyId: this.comId,
        CheckType: type,
        Value: value
      })
    },
    async save() {
      if (this.loading) {
        return
      }
      this.loading = true
      const data = await formMethods.validate()
      if (data == null) {
        this.loading = false
        return
      }
      if (data.FileId && data.FileId.length > 0) {
        data.FileId = data.FileId[0]
        data.UserHead = data.UserHead[0]
      } else {
        data.FileId = null
        data.UserHead = null
      }
      if (this.empId == null) {
        this.add(data)
      } else {
        this.set(data)
      }
    },
    async add(data) {
      data.CompanyId = this.comId
      await empApi.add(this.emp)
      this.$message({
        type: 'success',
        message: '添加成功!'
      })
      this.loading = false
      this.$router.replace({ name: 'emp' })
    },
    async set(data) {
      await empApi.set(this.empId, data)
      this.$message({
        type: 'success',
        message: '保存成功!'
      })
      this.loading = false
      this.$router.replace({ name: 'emp' })
    },
    async reset() {
      this.loading = false
      if (this.empId == null) {
        this.empData = {}
        this.title = '新增员工'
      } else {
        const res = await empApi.get(this.empId)
        this.empData = res
        this.title = '编辑员工资料'
      }
      this.initScheme()
    },
    initScheme() {
      const list = [
        {
          field: 'basic',
          label: '基础信息',
          component: 'Divider'
        },
        {
          field: 'EmpName',
          label: '员工名',
          component: 'Input',
          componentProps: {
            maxlength: 100,
            placeholder: '员工名'
          }
        },
        {
          field: 'EmpNo',
          label: '员工编号',
          component: 'Input',
          componentProps: {
            maxlength: 50,
            placeholder: '员工名'
          }
        },
        {
          field: 'Sex',
          label: '性别',
          component: 'EnumItem',
          componentProps: {
            dicKey: HrEnumDic.hrUserSex,
            placeholder: '请选择性别',
            filters: [0]
          }
        },
        {
          field: 'DeptId',
          label: '入职部门',
          component: 'DeptSelect',
          componentProps: {
            isChioseUnit: false,
            placeholder: '选择入职部门'
          }
        },
        {
          field: 'PostCode',
          label: '入职岗位',
          component: 'TreeDicItem',
          componentProps: {
            dicId: HrItemDic.post,
            multiple: true,
            placeholder: '选择入职岗位'
          }
        },
        {
          field: 'TitleCode',
          label: '入职职务',
          component: 'DicItem',
          componentProps: {
            dicId: HrItemDic.title,
            multiple: true,
            placeholder: '选择入职岗位'
          }
        },
        {
          field: 'UserType',
          label: '员工类型',
          component: 'EnumItem',
          componentProps: {
            dicKey: HrEnumDic.hrUserType,
            placeholder: '选择员工类型'
          }
        },
        {
          field: 'Show',
          label: '备注说明',
          component: 'Input',
          colProps: {
            span: 24
          },
          componentProps: {
            type: 'textarea',
            maxlength: 255,
            placeholder: '备注说明'
          }
        },
        {
          field: 'userDatum',
          label: '个人资料',
          component: 'Divider'
        },
        {
          field: 'Phone',
          label: '手机号',
          component: 'Input',
          componentProps: {
            maxlength: 15,
            placeholder: '请填入员工手机号'
          }
        },
        {
          field: 'BackupPhone',
          label: '备用联系电话',
          component: 'Input',
          componentProps: {
            maxlength: 50,
            placeholder: '备用联系电话'
          }
        },
        {
          field: 'Nation',
          label: '民族',
          component: 'DicItem',
          componentProps: {
            dicId: HrItemDic.nation,
            placeholder: '选择所属民族'
          }
        },
        {
          field: 'IDCard',
          label: '身份证号',
          component: 'Input',
          componentProps: {
            maxlength: 20,
            placeholder: '身份证号',
            on: {
              change: (val) => {
                if (val && val.length >= 14) {
                  const date =
                    val.substring(6, 10) + '-' + val.substring(10, 12) + '-' + val.substring(12, 14)
                  formMethods.setValues({
                    Birthday: date
                  })
                }
              }
            }
          }
        },
        {
          field: 'Birthday',
          label: '生日',
          component: 'DatePicker',
          componentProps: {
            type: 'date',
            placeholder: '员工生日'
          }
        },
        {
          field: 'Email',
          label: 'Email',
          component: 'Input',
          componentProps: {
            maxlength: 255,
            placeholder: '邮箱地址'
          }
        },
        {
          field: 'Address',
          label: '住址',
          component: 'Input',
          componentProps: {
            maxlength: 100,
            placeholder: '住址'
          }
        },
        {
          field: 'FileId',
          label: '上传头像',
          component: 'ImageUp',
          colProps: {
            span: 24
          },
          componentProps: {
            fileKey: 'EmpHead',
            linkBizPk: this.empId,
            urlField: 'UserHead'
          }
        }
      ]
      if (this.empId != null) {
        this.schema = list.filter(
          (a) => a.field != 'PostCode' && a.field != 'TitleCode' && a.field != 'DeptId'
        )
      } else {
        this.schema = list
      }
    }
  }
}
</script>
